package linkedstack

import (
	"errors"
	"go_algorithm/singlelinkedlist"
)

// 栈
type Stack struct {
	linkedList *singlelinkedlist.SingleLinkedList
	length     int
}

// 初始化栈
func NewStack(length int) *Stack {
	return &Stack{singlelinkedlist.NewSingleLinkedList(), length}
}

// 入栈
func (this *Stack) push(v interface{}) error {
	// 栈满
	if this.length <= this.linkedList.GetLength().(int) {
		return errors.New("栈满")
	}

	// 入栈
	this.linkedList.InsertToHead(v)
	return nil
}

// 出栈
func (this *Stack) pop() (interface{}, error) {

	// 栈空
	if this.linkedList.GetLength() == 0 {
		return nil, errors.New("栈空")
	}

	cur := this.linkedList.GetHead().GetNext()
	this.linkedList.DeleteSingleListNode(cur)
	return cur.GetValue(), nil
}
